<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>

  </style>
</head>

<body>
  <div id="app">
    <div v-if="isShow">
      <label for="nicheng">昵称</label>
      <input type="text" name="nicheng" id="nicheng" v-model="name">
      <label for="room">房间号</label>
      <input type="text" name="room" id="room" v-model="roomId">
      <button @click="into">登录聊天室</button>
    </div>
    <div v-else>
      <ul>
        <li v-for="(item,index) in items" :key="index">
          {{item.message}}
        </li>
      </ul>
      <div class="ctrl">
        <input type="text" name="" id="" v-model="inpVal">
        <button @click="submits">发送</button>
      </div>
    </div>
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      isShow: true,
      inpVal: '',
      items: [

      ],
      wsHandle: '',
      name: '',
      roomId: '',
      handler: '',
      reconnect: ''
    },
    methods: {
      init() {
        this.wsHandle = new WebSocket('ws://127.0.0.1:8000')
        this.wsHandle.onopen = this.onOpen
        this.wsHandle.onmessage = this.onMessage
        this.wsHandle.onerror = this.onError
      },
      into() {
        if (this.name.trim() === '') {
          alert('请输入用户名')
          return
        }
        this.wsHandle.send(JSON.stringify({
          event: 'login',
          name: this.name,
          roomId: this.roomId
        }))
        this.isShow = false
      },
      submits() {
        this.wsHandle.send(JSON.stringify({
          name: this.name,
          message: this.inpVal
        }))
        this.items.push({
          message: this.name + ': ' + this.inpVal
        })
        this.inpVal = ''

      },
      onMessage(evt) {
        let msg = JSON.parse(evt.data)
        if (msg.event === 'noAuth') {
          console.log(msg.message)
          return
        }
        if (msg.event === 'heartbeat' && msg.message === 'ping') {
          this.checkServer()
          this.wsHandle.send(JSON.stringify({
            event: 'heartbeat',
            message: 'pong',
            name: this.name
          }))
          return
        }
        if (msg.event === 'login') {
          this.items.push({
            message: `欢迎${msg.name}进入，当前人数${msg.nums}`
          })
        } else if (msg.event === 'logout') {
          this.items.push({
            message: msg.name + ': 退出聊天室'
          })
        } else {
          this.items.push({
            message: msg.name + ': ' + msg.message
          })
        }
      },
      onOpen() {
        this.wsHandle.send(JSON.stringify({
          event: 'auth',
          message: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vdGJhciIsImlhdCI6MTY1MTU5NjgwNCwiZXhwIjoxNjUyODkyODA0fQ.vZU1rYxb-nMecQMBv0iBepNl0Q-YtznkS-bExTYQG9Y'
        }))
        console.log('client is connect')
        this.checkServer()
      },
      checkServer() {
        console.log('---------------')
        console.log('beat')
        console.log('---------------')
        clearTimeout(this.handler)
        const _this = this
        this.handler = setTimeout(function () {
          _this.onClose()
          _this.init()
        }, 5000 + 1000)
      },
      onClose() {
        this.wsHandle.close()
      },
      onError() {
        const _this = this
        clearTimeout(this.reconnect)
        this.reconnect =  setTimeout(() => {
          console.log('!!!!!!!!!!!!!')
          console.log('reconnect webSocket!!')
          console.log('!!!!!!!!!!!!!')
          _this.init()
        }, 5000)
      }
    },
    mounted() {
      this.init()
    }
  })
</script>

</html>